import { ReactComponent as FileIcon } from '@/assets/images/icon-file.svg';
import Icon, { DeleteOutlined, EyeOutlined } from '@ant-design/icons';
import { UploadFile } from 'antd';
import { useMemo, useState } from 'react';
import { Ellipsis } from '../Ellipsis';
import { UploaderListItemRender } from './UploaderStyle';
import { checkIsImage, getFileName, getImagePreview } from './UploaderUtil';

interface Props {
  file: UploadFile;
  removeChange: (file: UploadFile) => void;
  previewChange?: (file: UploadFile) => void;
}

export const UploaderListItem: React.FC<Props> = (props) => {
  const { file, removeChange, previewChange } = props;

  const [previewImage, setPreviewImage] = useState('');

  const isImage = useMemo(() => {
    return checkIsImage(file);
  }, [file]);

  useMemo(async () => {
    let src = await getImagePreview(file);

    setPreviewImage(src);
  }, [file]);

  return (
    <UploaderListItemRender className="uploader-list-item">
      <div className="uploader-list-info">
        <span className="uploader-list-icon">
          {isImage && previewImage ? (
            <img
              alt=""
              src={previewImage as any}
              onClick={() => previewChange && previewChange(file)}
              style={{ cursor: 'pointer' }}
            />
          ) : (
            <Icon component={FileIcon} />
          )}
        </span>
        <span className="uploader-list-name">
          <Ellipsis lines={1} text={getFileName(file.name)} />
        </span>
      </div>
      <div className="uploader-list-action">
        {isImage ? (
          <span className="uploader-list-view">
            <EyeOutlined onClick={() => previewChange && previewChange(file)} />
          </span>
        ) : null}
        <span className="uploader-list-remove">
          <DeleteOutlined onClick={() => removeChange(file)} />
        </span>
      </div>
    </UploaderListItemRender>
  );
};
